<template>
    <el-dialog
        class="setting-dialog"
        align-center
        title="设置"
        v-model="visible"
        :close-on-click-modal="false"
        :width="form.emplaceSet.length ? 1000 : 600"
        @close="closeCallback()">
        <el-form :model="form" ref="formRef" label-width="auto" :rules="rules" @submit.prevent>
            <el-form-item label="主体名称:">{{ form.merchantName }}</el-form-item>
            <el-form-item label="登录号:">{{ form.loginNo }}</el-form-item>
            <el-form-item label="支付手续费:" class="feeRatio" prop="type">
                <el-radio-group v-model="form.type" @change="onRadioChange">
                    <el-radio :label="2">统一设置</el-radio>
                    <el-radio :label="1">自定义</el-radio>
                </el-radio-group>
                <template v-if="form.type === 1">
                    <el-form-item class="custom-form-item" prop="feeRatio">
                        <!-- <el-input-number
                            class="input_number"
                            v-model="form.feeRatio"
                            :min="0"
                            :max="50"
                            :precision="2"
                            :controls="false"
                            placeholder="请输入">
                        </el-input-number> -->
                        <NumberInput
                            class="input_number"
                            v-model="form.feeRatio"
                            placeholder="请输入"
                            :max="50"></NumberInput>
                    </el-form-item>
                    <span> %</span>
                </template>
            </el-form-item>
            <el-form-item label="分账设置:">
                <SubAccountDialog :exclude="excludes" @handle-confirm="getSubData"></SubAccountDialog>
                <template v-if="form?.emplaceSet?.length">
                    <el-table class="sub-class-table" :data="form.emplaceSet" width="800">
                        <el-table-column v-for="{ prop, ...rest } in subColumns" :key="prop" :prop="prop" v-bind="rest">
                            <template #default="{ row, $index }">
                                <template v-if="prop === 'name'">
                                    {{ row.name || row.cardName || '-' }}<br />{{ row.loginNo }}
                                </template>
                                <template v-if="prop === 'corpRelation'">
                                    <span v-for="item in row?.corpRelation" :key="item.corpId">
                                        <span>商户ID：{{ item.corpId }}</span
                                        ><br />
                                        <span>商城名称：{{ item.corpName }}</span
                                        ><br />
                                    </span>
                                    <span v-if="!row?.corpRelation || !row?.corpRelation?.length">-</span>
                                </template>
                                <template v-if="prop === 'shopRelation'">
                                    <span v-for="item in row?.shopRelation" :key="item.shopId">
                                        <span>门店ID：{{ item.shopId }}</span
                                        ><br />
                                        <span>门店名称：{{ item.shopName }}</span
                                        ><br />
                                    </span>
                                    <span v-if="!row?.shopRelation || !row?.shopRelation?.length">-</span>
                                </template>
                                <el-form-item
                                    v-if="prop === 'ratio'"
                                    class="price-form-item"
                                    label-width="0px"
                                    :prop="'emplaceSet.' + $index + '.ratio'"
                                    :rules="[
                                        {
                                            required: true,
                                            validator: checkRatio,
                                            trigger: 'blur'
                                        }
                                    ]">
                                    <NumberInput
                                        class="custom-number"
                                        v-model="row.ratio"
                                        :max="99.99"
                                        placeholder="请输入"></NumberInput>
                                    <!-- <el-input
                                        :model-value="row.ratio"
                                        placeholder="请输入"
                                        class="custom-number" /> -->
                                </el-form-item>
                                <el-popconfirm
                                    v-if="prop === 'operation'"
                                    :key="row.id"
                                    placement="top"
                                    width="250px"
                                    title="确定要删除吗？"
                                    @confirm="handleRemove($index)"
                                    confirm-button-text="确定"
                                    cancel-button-text="取消">
                                    <template #reference>
                                        <el-button v-if="prop === 'operation'" size="small"> 删除</el-button>
                                    </template>
                                </el-popconfirm>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- todo:计算比例 -->
                    <div class="custom-tip">总分账比例（包括平台抽成）：{{ ratio }}%</div>
                </template>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="custom-footer">
                <div>
                    <el-button plain @click="handleVisible(false)">取消</el-button>
                    <el-button type="primary" @click="handleConfirm">确认</el-button>
                </div>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, unref, computed, onMounted, inject } from 'vue';
import { cloneDeep, isEmpty } from '@/commons/utils';
import { ElMessage } from 'element-plus';
import request from '@/request/index';
import SubAccountDialog from './subAccountDialog.vue';
import NumberInput from '@/components/NumberInput.vue';

/* ---------------------------------- 父级通信 start ---------------------------------- */
const emit = defineEmits(['handle-confirm']);
const props = defineProps({
    // 是否显示控制按钮
    btnVisible: {
        type: Boolean,
        default: true
    },
    // 是否禁用
    disabled: {
        type: Boolean,
        default: false
    }
});
const currency = inject('currency');
/* ---------------------------------- 父级通信 end ---------------------------------- */

/* ---------------------------------- 弹窗表单 start ---------------------------------- */
const form = reactive({
    type: '',
    feeRatio: null,
    emplaceSet: []
}); // 表单
const formClone = cloneDeep(form); // 表单备份
const formRef = ref();
let selectedLoginNoIds = reactive([]);
const checkRatio = (rule, value, callback) => {
    if ([null, undefined].includes(value)) {
        return callback('请填写分账比例');
    }
    callback();
};
const rules = reactive({
    type: [{ required: true, message: '请选择支付手续费类型', trigger: 'change' }],
    feeRatio: [{ required: true, message: '请输入手续费', trigger: 'blur' }]
}); // 表单验证规则

const subColumns = reactive([
    { label: '类型', prop: 'accountTypeName', width: '100' },
    { label: '主体名称/登录号', prop: 'name', minWidth: '150', showOverflowTooltip: true },
    { label: '关联商户', prop: 'corpRelation', minWidth: '150', showOverflowTooltip: true },
    { label: '关联门店', prop: 'shopRelation', minWidth: '150', showOverflowTooltip: true },
    { label: '分账比例（%）', prop: 'ratio', minWidth: '150' },
    { label: '操作', prop: 'operation', width: '100' }
]);

/* ---------------------------------- 弹窗表单 end ---------------------------------- */

/* ---------------------------------- 控制弹窗 start ---------------------------------- */
let loading = ref(false);
let visible = ref(false); // 弹窗展示隐藏
// 展示隐藏
const handleVisible = (isVisible = false) => {
    if (props.disabled) {
        return;
    }
    visible.value = isVisible;
};
const excludes = computed(() => {
    return [currentLoginNo.value, ...(form.emplaceSet || []).map(item => item.loginNo)];
});
// 控制打开窗口并展示设置详情
let currentLoginNo = ref();
const openDialog = async row => {
    // const { data } = await request('withdrawInfo', { id: row.id });
    // const _data = cloneDeep(data);
    // _data.auditResult = _data.auditResult || 1;
    // const { data } = await request('getQiyiPremiumServ', { corpId: row.id });
    const [{ data }, listRes] = await Promise.all([
        request('getQiyiPremiumServ', { corpId: row.id, loginNo: row.loginNo }),
        request('bhtAccountSelectedList', { loginNo: row.loginNo })
    ]);
    // 弹窗值
    form.type = data?.type || 1;
    form.feeRatio = ![null, undefined].includes(data?.feeRatio) ? data?.feeRatio / 1 : data?.feeRatio;
    form.merchantName = row.name;
    form.loginNo = row.loginNo;
    form.corpId = row.id;
    form.paySequenceNo = row.paySequenceNo;
    currentLoginNo.value = row.loginNo;
    // 已选中的分账方
    form.emplaceSet.length = 0;
    Object.assign(
        form.emplaceSet,
        (listRes?.data?.data || []).map(item => {
            item.ratio = currency(item.ratio || 0, { precision: 4 }).multiply(100).value;
            return item;
        })
    );
    selectedLoginNoIds.length = 0;
    selectedLoginNoIds = (listRes?.data?.data || []).map(item => item.selectedLoginNoId);
    handleVisible(true);
};

// 重置验证
const resetFields = () => {
    unref(formRef).resetFields();
};
// 清空验证
const clearValidate = field => {
    unref(formRef).clearValidate(field);
};
// 校验验证
const validateField = field => {
    unref(formRef).validateField(field);
};
// 确认按钮
const handleConfirm = async () => {
    // 表单验证
    unref(formRef)?.validate(async (valid, fields) => {
        if (valid) {
            if (ratio.value > 99.5) {
                ElMessage.error('总分账比例不能超过99.5%');
                return;
            }
            const _form = cloneDeep(form);
            if (_form.type == 2) {
                delete _form.feeRatio;
            } else {
                _form.feeRatio = currency(_form.feeRatio || 0).divide(1).value;
            }
            delete _form.merchantName;
            // 删除的ids
            const emplaceSetIds = _form.emplaceSet.map(item => item.selectedLoginNoId);
            const delSelectIds = selectedLoginNoIds.filter(item => !emplaceSetIds.includes(item));
            _form.emplaceSet = _form.emplaceSet.map(item => {
                item.ratio = currency(item.ratio, { precision: 4 }).divide(100).value;
                delete item.accountTypeName;
                return item;
            });
            await request('setQiyiPremiumServ', { ..._form, delSelectIds });
            ElMessage.success('设置成功');
            emit('handle-confirm');
            handleVisible(false);
        } else {
            unref(formRef).scrollToField(Object.keys(fields)?.[0]);
        }
    });
};
// 关闭后重置表单
const closeCallback = visible => {
    resetFields();
    Object.assign(form, cloneDeep(formClone));
};

// 切换radio
const onRadioChange = v => {
    form.feeRatio = null;
};

// 获取选中的分账方getSubData
const getSubData = selected => {
    // todo:格式化
    if (selected && selected.length) {
        const selectedList = selected.map(item => {
            return {
                accountTypeName: item.accountTypeName,
                // accountId: item.id, //宝户账号ID
                tenantId: 0, // 目前没用，和后端暂定0
                shopId: 0, // 目前没用，和后端暂定0
                type: item.accountType, //  '账户类型1企业账户2个人账户3个体账户'
                name: item.cardName, // '主体姓名'
                loginNo: item.loginNo, // '登录号'
                ratio: item.ratio, // COMMENT '分账比例'
                corpRelation: item.corpRelation,
                shopRelation: item.shopRelation,
                contractNo: item.contractNo
            };
        });
        form.emplaceSet.push(...selectedList);
    }
};

// 删除已选的分账方
const handleRemove = index => {
    form.emplaceSet.splice(index, 1);
};

/* ---------------------------------- 控制弹窗 end ---------------------------------- */

let feeRatio = ref(0);
// 计算总比例
const ratio = computed(() => {
    const subRaido = form?.emplaceSet?.reduce((prev, curr) => {
        return currency(curr?.ratio || 0)
            .divide(1)
            .add(prev).value;
    }, 0);
    return currency(subRaido)
        .add(form.type == 1 ? form.feeRatio || 0 : feeRatio.value || 0)
        .divide(1).value;
});

const getBaseRatio = async () => {
    // 获取统一设置比例
    const { data } = await request('getQiyiPremiumServ');
    if (data?.feeRatio >= 0) {
        feeRatio.value = +data.feeRatio;
    }
};

onMounted(() => {
    getBaseRatio();
});

defineExpose({
    openDialog
});
</script>

<style lang="scss">
.setting {
    &-dialog {
        max-width: 1000px;
        min-width: 600px;
        /* transition: width 0.3s; */
        & > .el-dialog__body {
            max-height: 500px;
            overflow-y: auto;
        }
        .account-name {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #666666;
        }
        .sub-class-table {
            margin: 10px 0;
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #33302d;
            border-bottom: 1px solid #eaeaea !important;
            /* min-height: 570px; */
            th.el-table__cell {
                padding: 8px 0;
                font-size: 14px;
                font-family: PingFangSC-Medium, PingFang SC;
                font-weight: 500;
                color: #33302d;
            }
            .el-table__cell {
                padding: 0;
                .cell {
                    .el-form-item {
                        margin: 16px 0;
                    }
                }
            }
        }
    }
    &-btn {
        display: inline-flex;
        .el-button.is-link {
            padding: 0;
            &:hover,
            &:focus {
                border-color: transparent !important;
                background-color: transparent !important;
            }
            &:hover {
                color: var(--el-button-hover-link-text-color) !important;
            }
        }
    }
}
</style>
<style lang="scss" scoped>
.setting {
    &-dialog {
        .input_number {
            width: 80px;
            margin: 0 4px;
        }
        .custom-form-item {
            :deep .el-form-item__label-wrap {
                margin-left: 0 !important;
            }
        }
        .custom-tip {
            color: var(--el-color-danger);
        }
    }
}
</style>
